package ccot.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * Servlet implementation class QuestionServlet
 */
@WebServlet("/QuestionServlet")
public class QuestionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private DataSource dataSource;
    private Connection connection;
    private Statement statement;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public QuestionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init() throws ServletException {
        try {
            Context initContext  = new InitialContext();
            dataSource = (DataSource)initContext.lookup("java:comp/env/jdbc/ccot");
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }
    
    private boolean createQuestion(
    	String question, 
    	String type, 
    	String choice_a, 
    	String choice_b, 
    	String choice_c, 
    	String choice_d, 
    	String choice_e, 
    	String choice_answer, 
    	String text_answer,
    	int course_id,
    	String chapter,
    	String difficulty
    ) {
    	boolean success = false;
    	
    	ResultSet resultSet = null;
    	try {
    		connection = dataSource.getConnection();
    		statement = connection.createStatement();
    		String query = "SELECT * FROM questions WHERE question='" + question + "'";
    		resultSet = statement.executeQuery(query);
    		if (resultSet.next()) {
    			success = false;
    			return success;
    		}
    		
    		String sql = "INSERT INTO questions (question, type, choice_a, choice_b, choice_c, choice_d, choice_e, choice_answer, text_answer, course_id, chapter, difficulty) VALUES('" 
    				+ question + "','" 
    				+ type + "','"
    				+ choice_a + "','"
    				+ choice_b + "','"
    				+ choice_c + "','"
    				+ choice_e + "','"
    				+ choice_e + "','"
    				+ choice_answer + "','"
    				+ text_answer + "','"
    				+ course_id + "','" 
    				+ chapter + "','"
    				+ difficulty + "')";
    		System.out.println(sql);
    		statement.executeUpdate(sql);
    		success = true;
    	} catch (SQLException e) {
    		e.printStackTrace();
    	} finally {
    		try {
    			if (null != statement) {
    				statement.close();
    			}
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		try {
    			if (null != connection) {
    				connection.close();
    			}
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    	}
    	
    	return success;
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	PrintWriter out = response.getWriter();
    	
    	String action = request.getParameter("action");
    	if (action.equals("create")) {
    		String question = new String(request.getParameter("question").getBytes("ISO-8859-1"), "UTF-8");
    		String type = new String(request.getParameter("type").getBytes("ISO-8859-1"), "UTF-8");
    		String choice_a = new String(request.getParameter("choice_a").getBytes("ISO-8859-1"), "UTF-8");
    		String choice_b = new String(request.getParameter("choice_b").getBytes("ISO-8859-1"), "UTF-8");
    		String choice_c = new String(request.getParameter("choice_c").getBytes("ISO-8859-1"), "UTF-8");
    		String choice_d = new String(request.getParameter("choice_d").getBytes("ISO-8859-1"), "UTF-8");
    		String choice_e = new String(request.getParameter("choice_e").getBytes("ISO-8859-1"), "UTF-8");
    		String choice_answer = new String(request.getParameter("choice_answer").getBytes("ISO-8859-1"), "UTF-8");
    		String text_answer = new String(request.getParameter("text_answer").getBytes("ISO-8859-1"), "UTF-8");
    		int course_id = Integer.parseInt(request.getParameter("course_id"));
    		String chapter = new String(request.getParameter("chapter").getBytes("ISO-8859-1"), "UTF-8");
    		String difficulty = new String(request.getParameter("difficulty").getBytes("ISO-8859-1"), "UTF-8");
    		
    		boolean success = createQuestion(question, type, choice_a, choice_b, choice_c, choice_d, choice_e, choice_answer, text_answer, course_id, chapter, difficulty);
        	if (success) {
        		out.println("<p>题目创建成功</p>");
        	} else {
        		out.println("<p>无法创建题目，该题目或许已经存在！</p>");
        	}
    	}
    	
    	
    	ResultSet resultSet = null;
    	try {
    		connection = dataSource.getConnection();
    		statement = connection.createStatement();
    		String query = "select * from questions limit 10";
    		resultSet = statement.executeQuery(query);
    		if (resultSet.next()) {
    			String question = resultSet.getString("question");
    			String type = resultSet.getString("type");
    			out.println("<p>" + question + "," + type + "</p>");
    		} else {
    			System.out.println("nothing");
    			out.println("nothing");
    		}
    	} catch (SQLException e) {
    		e.printStackTrace();
    	} finally {
    		try {
    			if (null != resultSet) {
    				resultSet.close();
    			}
    		} catch (SQLException e) {
				e.printStackTrace();
			}
    		try {
    			if (null != statement) {
    				statement.close();
    			}
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		try {
    			if (null != connection) {
    				connection.close();
    			}
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    	}
    }


	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		processRequest(request, response);
	}

}
